// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init()
const TcbRouter = require('tcb-router')
const db = cloud.database()
const blogCollection = db.collection('blog')

// 云函数入口函数
exports.main = async (event, context) => {
  let app = new TcbRouter({event})
  let { OPENID } = cloud.getWXContext()
  //保存博客入库
  app.router('save',async(ctx,next) => {
    let { fileIds ,content ,avatarUrl,nickName } = event
    await blogCollection.add({
      data:{
        fileIds ,
        content ,
        avatarUrl,
        nickName,
        openId:OPENID,
        createTime:db.serverDate()
      }
    })
    ctx.body = {
      code:0,
      msg:''
    }
  })

  //获取博客列表
  app.router('list', async (ctx,next) => {
    let keyword = event.keyword
    let obj = {}
    if (keyword) {
      obj = {
        content: new RegExp(keyword,'i')
      }
    }
    let { page,limit } = event
    page = +page
    limit = +limit
    let { data } = await blogCollection.where(obj).skip((page - 1) * limit).limit(limit).orderBy('createTime','desc').get()
    ctx.body = {
      code:0,
      data
    }
  })
  return app.serve()
}
